#include "Order.hh"
#include "Bug.h"
#include <algorithm>


std::ostream & 
Order::dump(std::ostream & os)
{
  for (Order::const_iterator it=begin(); it != end(); ++it)
    {
      os << it->cost << " : " << torus.to_str(it->from,it->to);
      os << std::endl;
    }

  return os;
}


std::ostream & 
Order::dump_plan(std::ostream & os, action_plan_t & plan)
{
  for (action_plan_t::const_iterator it=plan.begin(); it != plan.end(); ++it)
    {
      os << torus.to_str(it->first,it->second);
      os << std::endl;
    }

  return os;
}


void 
Order::proposeAction(uLocation from, uLocation to, double w)
{
  push_back(Option(from,to,w));
}


void 
Order::execute(State & s)
{
  TRACK();
  Map<Square> & map(s.map);
    

#if DEBUG
  bug << "* moves values" << std::endl;
  sum_up(*this);
  std::sort(begin(),end(), by_decreasing_cost);
  std::stable_sort(begin(),end(),by_ant);
  dump(bug.file);
#endif 

  action_plan_t plan(get_maximal_cost_plan(*this));
		     
  bug << "* selected moves" << std::endl;
  dump_plan(bug.file,plan);

  bug << "* moving" << std::endl;
  unsigned changes = 1;
  while(changes>0)
    {
      changes = 0;
    

      for(action_plan_t::const_iterator it = plan.begin();
	  it!=plan.end(); ++it)
	{
	  if(isGround(map[it->second]))
	    { // already valid move
	      bug << torus.to_str(it->first,it->second) << std::endl;
	      unsigned direction = torus.getDirection(it->first,it->second);
	      if(direction<Torus::TDIRECTIONS)
		{
		  changes++;
		  s.makeMove(it->first, direction);
		}
	    }
	}
      bug << "changes: " << changes << std::endl;
    }
}



	
